﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Clotho.MdStore {
	public class MarkdownFile {
		private MdFactory factory; 
		public MdFactory Factory { get => factory; set => factory = value; }
		public MarkdownFile(MdFactory factory) {
			this.Factory = factory;
		}

		public string[] writeToFile(IEnumerable<IMdItem>  items) {
			Queue<string> str_queue = new Queue<string>();
			foreach (IMdItem item in items) {
				getMd(item, 0, ref str_queue);
			}
			return str_queue.ToArray();
		}

		static void getMd(IMdItem item, int level, ref Queue<string> str_array) {
			string head = new string('#',level+1);
			head += $" `{item.GetType().Name}`{item.Name}";
			item.getDescription();
			str_array.Enqueue(head);
			foreach (var str in item.getDescription()) {
				str_array.Enqueue(str);
			}
			foreach (var sub_item in item.Sub_items) {
				getMd(sub_item, level + 1, ref str_array);
			}
			return;
		}

		public IEnumerable<IMdItem> readFile(string[] file_lines) {
			int ptr = 0;
			Queue<IMdItem> item_queue = new Queue<IMdItem>();
			while (ptr< file_lines.Length) {
				var item = extractMdItem(file_lines, ref ptr);
				if(item!= null) {
					item_queue.Enqueue(item);
				}
			}
			return item_queue;
		}
		public IMdItem extractMdItem(string[] desc, ref int ptr) {
			if (desc[ptr].Substring(0, 1) != "#") {
				return null;
			}
			
			//读取这一行作为Item头。
			string[] str_a = desc[ptr].Split('`');
			string end_str = str_a[0];
			IMdItem item = factory.bulid(str_a[1]);
			item.Name = str_a[2];
			ptr ++;

			//读取剩下的内容直到下一个#开头的行
			int end = Array.FindIndex(desc, ptr, st => st.Substring(0, 1) == "#");
			if (end == -1) { end = desc.Length; }//或者直到最后一行			
			item.setDescription(desc, ptr, end-ptr);//用这些行初始化
			ptr = end;

			while (true) {
				if (ptr == desc.Length) {
					return item;
				}
				if (desc[ptr].Substring(0, end_str.Length) == end_str) {
					return item;
				}
				var sub_item = extractMdItem(desc, ref ptr);
				if (sub_item != null) {
					item.addItem(sub_item);
				}
			}
		}
	}
}
